package cn.boy.gui.student;

import cn.boy.domain.Adminstrator;
import cn.boy.domain.Student;
import cn.boy.gui.adminstrator.AdminInfoActivity;
import cn.boy.gui.adminstrator.AdminInfoEditActivity;
import cn.boy.home.HomeApplication;
import cn.boy.home.R;
import cn.boy.service.HomeService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class StudentInfoEditActivity extends Activity {

	EditText txtNO;
	EditText txtName;
	EditText txtAge;
	EditText txtSex;
	EditText txtDorm;
	EditText txtClassInfo;
	Button submitButton;
	
	HomeApplication app;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.student_info_edit);
		
		findViews();
		
		app = (HomeApplication) getApplicationContext();
		
		initInfo();
		
		submitButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				String no = txtNO.getText().toString();
				String name = txtName.getText().toString();
				String age = txtAge.getText().toString();
				String sex = txtSex.getText().toString();
				String dorm = txtDorm.getText().toString();
				String classInfo = txtClassInfo.getText().toString();
				Student student = new Student(no, name, "", sex, age, dorm, classInfo);
				app.setStudent(student);
				uploadInfo(student);
				launchActivity();
			}
		});
	}
	
	private void uploadInfo(final Student student) {
		new Thread(new Runnable() {
			
			public void run() {

				try {
					HomeService.updateInfo(student);
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
				
			}
		}).start();
		
	}
	
	private void launchActivity() {

		Intent intent = new Intent(StudentInfoEditActivity.this,StudentInfoActivity.class);
		startActivity(intent);
		finish();
	}
	
	private void initInfo() {
		Student student = app.getStudent();
		txtNO.setText(student.getNO());
		txtName.setText(student.getName());
		txtAge.setText(student.getAge());
		txtSex.setText(student.getSex());
		txtDorm.setText(student.getDormitoryNO());
		txtClassInfo.setText(student.getClassInfo());
		
	}

	private void findViews() {
		txtNO = (EditText)findViewById(R.id.et_student_no);
		txtName = (EditText)findViewById(R.id.et_student_name);
		txtAge = (EditText)findViewById(R.id.et_student_age);
		txtSex = (EditText)findViewById(R.id.et_student_sex);
		txtDorm = (EditText)findViewById(R.id.et_student_dorm);
		txtClassInfo = (EditText)findViewById(R.id.et_student_class);
		
		submitButton = (Button)findViewById(R.id.btn_submit);
	}
}
